package de.uniLuebeck.tcs.algorithmics;

public class SudokuInstance {
	
	private	int[] 	m_fields;
	private int		m_rows;
	private int		m_cols;
	
	public SudokuInstance(int[][] matrix) {
		m_rows = matrix.length;
		m_cols = matrix[0].length;
		
		m_fields = new int[m_rows * m_cols];
		for(int row = 0; row < m_rows; row++) {
			for(int col = 0; col < m_cols; col++) {
				m_fields[decodeCoordinate(row, col)] = matrix[row][col];
			}
		}
	}
	
	public SudokuInstance(SudokuInstance x) {
		this(x.getAsMatrix());
	}
	
	private int	decodeCoordinate(int row, int col) {
		return	(row * m_cols + col);
	}
	
	public int	getField(int i) {
		return	m_fields[i];
	}
	
	public int	getField(int row, int col) {
		return	m_fields[decodeCoordinate(row, col)];
	}
	
	public void	setField(int i, int value) {
		m_fields[i] = value;
	}
	
	public void	setField(int row, int col, int value) {
		m_fields[decodeCoordinate(row, col)] = value;
	}
	
	public int	getNextEmpty() {
		for(int i = 0; i < getNumberOfFields(); i++) {
			if(isEmpty(i)) {
				return	i;
			}
		}
		
		return	-1;
	}
	
	public boolean	isEmpty(int i) {
		return	(0 == getField(i));
	}
	
	public boolean	isEmpty(int row, int col) {
		return (0 == getField(row, col));
	}
	
	public int[][]	getAsMatrix() {
		int[][]	matrix =new int[m_rows][m_cols];
		for(int row = 0; row < m_rows; row++) {
			for(int col = 0; col < m_cols; col++) {
				matrix[row][col] = getField(row, col);
			}
		}
		return	matrix;
	}
	
	public int	getNumberOfRows() {
		return	m_rows;
	}
	
	public int	getNumberOfCols() {
		return	m_cols;
	}
	
	public int	getNumberOfFields() {
		return	(m_rows * m_cols);
	}
	
	public int[]	getNumberPossibleValues() {
		int[]	values = new int[m_rows];
		for(int i = 0; i < values.length; i++) {
			values[i] = i + 1;
		}
		return	values;
	}
	
	public void	printDebug() {
		for(int row = 0; row < m_rows; row++) {
			for(int col = 0; col < m_cols; col++) {
				System.out.print(getField(row, col) + " ");
			}
			System.out.println();
		}
		System.out.println();
	}
	
	public int	getNumberOfOpenFields() {
		int	openFields = 0;
		for(int i = 0; i < getNumberOfFields(); i++) {
			if(isEmpty(i)) {
				openFields++;
			}
		}
		
		return	openFields;
	}
}
